package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.utils.VtuzxUtil;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.request.PrdFeedRequest;
import com.wonder.app.request.PrdInstockRequest;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.MapToEntity;
import com.wonder.constant.BillNoGenerator;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PrdInstockServiceImpl extends ServiceImpl<PrdInstockDao, PrdInstock> implements PrdInstockService {
    private static final Logger _logger = LoggerFactory.getLogger(PrdInstockServiceImpl.class);
    @Autowired
    private PrdInstockService prdInstockService;
    @Autowired
    private  PrdInstockDao prdInstockDao;
    @Autowired
    private SysAdminService adminService;
    @Autowired
    private PrdInstockDetailDao prdInstockDetailDao;
    @Autowired
    private PrdInstockDetailService prdInstockDetailService;

    @Autowired
    private TrayDao trayDao;

    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;

    @Autowired
    private IVtuzxKingdeeService kingdeeService;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;
    @Autowired
    private SfcProplanService sfcProplanService;
    @Autowired
    private SfcProplanDao sfcProplanDao;
    @Autowired
    private SfcproplanDetailDao sfcproplanDetailDao;
    @Autowired
    private SfcproplanDetailService sfcproplanDetailService;

    @Autowired
    private SfcOptrptDao sfcOptrptDao;

    @Autowired
    private SfcOptrptService sfcOptrptService;

    @Autowired
    private SfcOptrptDetailDao sfcOptrptDetailDao;

    @Autowired
    private TrayService trayService;

    @Autowired
    private MoldMaterialService moldMaterialService;

    @Autowired
    private PrdIronTrayService prdIronTrayService;


    @Override
    public IPage<PrdInstock> selectList(PrdInstockRequest prdInstockRequest, Page<PrdInstock> page) {
        LambdaQueryWrapper<PrdInstock> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (prdInstockRequest.getFBillNo() != null){
            lambdaQueryWrapper.like(PrdInstock::getFBillNo,prdInstockRequest.getFBillNo());
        }

        if (prdInstockRequest.getFKDBILLNO() != null){
            lambdaQueryWrapper.like(PrdInstock::getFKDBILLNO,prdInstockRequest.getFKDBILLNO());
        }

        if (prdInstockRequest.getFBILLNOMO() != null){
            lambdaQueryWrapper.like(PrdInstock::getFBILLNOMO,prdInstockRequest.getFBILLNOMO());
        }

        if (prdInstockRequest.getFCREATEUSER() != null){
            lambdaQueryWrapper.like(PrdInstock::getFCREATEUSER,prdInstockRequest.getFCREATEUSER());
        }

        if (prdInstockRequest.getFWORKSHOPNAME() != null){
            lambdaQueryWrapper.like(PrdInstock::getFWORKSHOPNAME,prdInstockRequest.getFWORKSHOPNAME());
        }

        if (prdInstockRequest.getFSTOCKPEL() != null){
            lambdaQueryWrapper.like(PrdInstock::getFSTOCKPEL,prdInstockRequest.getFSTOCKPEL());
        }

        if (prdInstockRequest.getCreateTime() != null){
            Date[] orderDate = prdInstockRequest.getCreateTime();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(PrdInstock::getCreateTime, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(PrdInstock::getCreateTime,orderDate[1]);

        }
        lambdaQueryWrapper.orderByDesc(PrdInstock::getCreateTime);

//        if (prdInstockRequest.getFDATE() != null){
//            Date[] orderDate = prdInstockRequest.getFDATE();
//            if(orderDate.length>0)
//                lambdaQueryWrapper.ge(PrdInstock::getFDATE, orderDate[0]);
//            if(orderDate.length==2)
//                lambdaQueryWrapper.le(PrdInstock::getFDATE,orderDate[1]);
//
//        }
        lambdaQueryWrapper.orderByDesc(PrdInstock::getCreateTime);
        Page<PrdInstock> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }

    /**
     * 生产入库单明细详情
     * @param map
     * @return
     * @throws Exception
     */

    @Override
    public Map<String, Object> getPrdInstockDetail(Map<String, Object> map) {
        String billNo = map.get("billNo").toString();
        PrdInstock prdinstockform = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getFBillNo,billNo));
        List<PrdInstockDetail> prdinstockdetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO,billNo));
        Map<String,Object> data = new HashMap<>();
        data.put("data",prdinstockform);
        data.put("dataList",prdinstockdetailList);
        return data;
    }
    /**
     * 查询仓库集合
     * @return
     */
    private List<Map<String,Object>> selectStcokList(Long user_id) throws Exception{
        SysAdmin sysAdmin = adminService.getById(user_id);
        if (VtuzxUtil.isEmpty(sysAdmin.getStockNoList())){
            throw new RuntimeException("当前用户没有关联仓库,请维护");
        }
        String stockNoList = sysAdmin.getStockNoList();//仓库集合
        List<String> stockNos = Arrays.asList(stockNoList.split(","));
        String materialNoCond = org.springframework.util.StringUtils.collectionToDelimitedString(stockNos, ",", "'", "'");
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e){
            throw new RuntimeException("金蝶账号密码错误，请维护");
        }
        List<Map<String,Object>> dataList = new ArrayList<>();
        String cond = String.format("FNumber in (%s)",materialNoCond);
        List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                        "FName",
                        "FNumber"
                ),
                cond, null, 0, 0);
        if (!VtuzxUtil.isEmpty(materialQuery)) {
            for (VtuzxMap data : materialQuery){
                Map<String,Object> map =new HashMap<>();
                String fname = VtuzxUtil.getString(data,"FName");
                String FNumber = VtuzxUtil.getString(data,"FNumber");
                map.put("value",FNumber);
                map.put("text",fname);
                dataList.add(map);
            }
        }
        return dataList;
    }
    /**
     * 判断仓库是否启用仓位
     * @param stockNo
     * @return
     */
    private Boolean stockIsLoc(String stockNo) throws Exception{
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        Boolean FIsOpenLocation = false;
        //查询物料是够启用批号
        List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                        "FIsOpenLocation"//是否启用仓位
                ),
                String.format("FNumber = '%s'", stockNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(materialQuery)) {
            FIsOpenLocation = VtuzxUtil.getBoolean(materialQuery.get(0),"FIsOpenLocation");
        }
        return FIsOpenLocation;
    }

    /**
     * 查询仓库向下的仓位信息
     * @param stockNo
     * @return
     */
    private List<String> getlocationList(String stockNo) throws Exception{
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        List<String> dataList = new ArrayList<>();
        //查询物料是够启用批号
        List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                        "FFlexEntryId.fnumber",//仓位编码
                        "FFlexEntryName"//仓位名称
                ),
                String.format("FNumber = '%s'", stockNo), null, 0, 0);
        if (!VtuzxUtil.isEmpty(materialQuery)) {
            for (Map<String,Object> data : materialQuery){
                String locationNo = VtuzxUtil.getString(data,"FFlexEntryId.fnumber");
//				String locationName = VtuzxUtil.getString(data,"FFlexEntryName");
//				Map<String,Object> locMap = new HashMap<>();
//				locMap.put("value",locationNo);
//				locMap.put("text",locationName);
                dataList.add(locationNo);
            }

        }
        return dataList;
    }
    /**
     * 生产入库单手机端明细详情
     * @param map
     * @return
     * @throws Exception
     */

    @Override
    public Map<String, Object> getprdinstockde(Long user_id,Map<String, Object> map) throws Exception {
        String billNo = map.get("billNo").toString();
        PrdInstock prdinstockform = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getFBillNo,billNo));
        Boolean isquality = prdinstockform.getISQUALITY();
        String fstate = prdinstockform.getFSTATE();
        //校验是否质检，没有质检的话无法传金蝶
        if (isquality){
            throw new RuntimeException("托盘已质检");
        }
        if ("audit".equals(fstate)){
            throw new RuntimeException("托盘已入库");
        }
        List<PrdInstockDetail> prdinstockdetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO,billNo));
        //重新获取日期
        Date date = DateUtils.adjustDateIntock(new Date(), prdinstockform.getFWORKSHOPNAME());
        prdinstockform.setFDATE(date);
        Map<String,Object> data = new HashMap<>();
        data.put("data",prdinstockform);
        data.put("dataList",prdinstockdetailList);
        return data;
    }


    //"查询工序计划明细(手机端领料列表)"
    @Override
    public Map<String, Object> getProInstocklist(SysAdmin user,Map<String, Object> map) {
        int pageIndex = VtuzxUtil.getInt(map,"pageIndex");
        int pageSize = VtuzxUtil.getInt(map,"pageSize");
        String billNo = VtuzxUtil.getString(map,"billNo");//订单号
        String produceStr = user.getProduceList();
        List<String> produceNoList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(produceStr)){
            produceNoList = Arrays.asList(produceStr.split(","));
        }
        boolean quality = VtuzxUtil.getBoolean(map,"quality");//是否质检
        List<PrdInstock> dataList = prdInstockDao.getProInstocklist(pageSize,pageIndex * pageSize,billNo,quality,produceNoList);
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",dataList);
        return data;
    }

    /**
     * 质检生产入库单
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean auditPrdInspect(Long user_id,String userName, Map<String, Object> map) throws Exception {
        Map<String,Object> header = VtuzxUtil.getObject(map,"header");
        String workshopName = VtuzxUtil.getString(header,"fworkshopname");//车间
        String inStockTime = VtuzxUtil.getString(map,"inStockTime");
        List<Map<String,Object>> dataList = VtuzxUtil.getObject(map,"dataList");
        String billNo = VtuzxUtil.getString(header,"fbillNo");//入库单号
        PrdInstock prdInstock = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getFBillNo, billNo));
        String proplanno = prdInstock.getPROPLANNO();//工序号

        prdInstock.setISQUALITY(true);
        prdInstock.setQUALITYNAME(userName);
        prdInstock.setQUALITYTIME(new Date());
        prdInstock.setFDATE(DateUtils.strToDate(inStockTime,"yyyy-MM-dd"));
        List<PrdInstockDetail> prdInstockDetails = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO, billNo));
        //修改合格数量和实收数量
        for (PrdInstockDetail prdInstockDetail : prdInstockDetails){
            Long id = prdInstockDetail.getId();
            for (Map<String,Object> data : dataList){
                Long mapId = VtuzxUtil.getLong(data,"id");
                double unqualifiedqty = VtuzxUtil.getDouble(data,"unqualityqty");//不合格数量
                double outunqualifiedqty = VtuzxUtil.getDouble(data,"outunqualityqty");//外协不合格数量
//                double frealqty = VtuzxUtil.getDouble(data,"frealqty");//实收数量
                if(id.equals(mapId)){
                    prdInstockDetail.setUNQUALITYQTY(unqualifiedqty);
                    prdInstockDetail.setOUTUNQUALITYQTY(outunqualifiedqty);
//                    prdInstockDetail.setFREALQTY(frealqty);
                }

            }
        }

        //判断车间，如果是毛坯和砂芯库直接审核入库
        if (workshopName.contains("毛胚") || workshopName.contains("砂芯")){
            auditPrdInSM(user_id,userName,prdInstock,prdInstockDetails);
        } else {//如果是机加车间的金蝶生成汇报单
            String trayNo = prdInstock.getTRAYNO();//托盘号
            try {
                syncKingdeeOrderService.syncPrdReportJiJia(user_id,proplanno,trayNo);
                boolean hRes = prdInstockService.updateById(prdInstock);
                boolean deRes = prdInstockDetailService.updateBatchById(prdInstockDetails);
            }catch (Exception e){
                throw new RuntimeException(e.getMessage());
            }
        }

        return true;
//        return true;

    }

    /**
     * 审核入库单(毛坯和砂芯)
     * @param userName
     * @return
     * @throws Exception
     */
    public Boolean auditPrdInSM(Long user_id,String userName,PrdInstock prdInstock,List<PrdInstockDetail> detailList) throws Exception {
        String fworkshopname = prdInstock.getFWORKSHOPNAME();//车间
        Double fqty = 0.0;//入库外层收货数量
        Double failCount = 0.0;
        //数据库添加仓位信息
        for (PrdInstockDetail prdInstockDetail : detailList){
            double realQty = prdInstockDetail.getFREALQTY();//实收数量
            failCount += prdInstockDetail.getFAILQTY();//废料数量合计
            //砂芯车间入到砂芯库，毛坯车间入到毛坯库
            if(fworkshopname.contains("砂芯")){
                prdInstockDetail.setFSTOCKNAME("砂芯库");
                prdInstockDetail.setFSTOCKNUMBER("CK002");
            } else {
                prdInstockDetail.setFSTOCKNAME("毛胚库");
                prdInstockDetail.setFSTOCKNUMBER("CK003");
            }

            fqty += realQty;
        }
        prdInstockDetailService.saveOrUpdateBatch(detailList);
        //修改外层表单据为审核状态，添加审核时间和审核人
        prdInstock.setAUDITTIME(new DateTime());
        prdInstock.setAUDITUSERNAME(userName);
        prdInstock.setFSTATE("audit");
        prdInstock.setFQTY(fqty);
        boolean res = prdInstockService.saveOrUpdate(prdInstock);
        //审核后增加模具的使用次数
        moldMaterialService.addMoldUserCount(prdInstock);
        //传金蝶生产入库单
        try {
            syncKingdeeOrderService.syncPrdInsStockSM(user_id,prdInstock,detailList);
            //判断有没有废料数量,有的话传金蝶回材库
            if(failCount > 0){
                syncKingdeeOrderService.syncPrdInsStockHuiCaiSM(user_id,prdInstock,detailList,failCount);
            }
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }


        return res;
    }

    /**
     * 审核入库单
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean auditPrdIn(Long user_id,String userName, Map<String, Object> map) throws Exception {
        String billNo = VtuzxUtil.getString(map,"billNo");
        String inStockTime = VtuzxUtil.getString(map,"inStockTime");
        List<Map<String,Object>> detailList = VtuzxUtil.getObject(map,"dataList");
        PrdInstock prdInstock = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>().eq(PrdInstock::getFBillNo, billNo));
        List<PrdInstockDetail> prdInstockDetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO, billNo));
        String proplanno = prdInstock.getPROPLANNO();//工序计划单号
        Map<String,Object> dataMap = new HashMap<>();//key:单号+id.val:仓库，仓位，仓库名称,实收数量
        Double fqty = 0.0;//入库外层收货数量
        String trayLocationNo = "";//仓位，托盘入到哪个仓位
        String trayStockNo = "";//仓库
        for (Map<String,Object> data : detailList){
            int id = VtuzxUtil.getInt(data,"id");
            String detailNo = VtuzxUtil.getString(data,"fbillno");
            String stockNo = VtuzxUtil.getString(data,"fstocknumber");
            String stockName = VtuzxUtil.getString(data,"fstockname");
            String locationNo = VtuzxUtil.getString(data,"locationNo");
            boolean isLocation = VtuzxUtil.getBoolean(data,"isLocation");
            double realQty = VtuzxUtil.getDouble(data,"frealqty");//实收数量
            List<String> locationList = VtuzxUtil.getObject(data,"locationList");

            if (VtuzxUtil.isEmpty(stockNo)){
                throw new RuntimeException("请录入仓库");
            }
            if (isLocation){
                if (VtuzxUtil.isEmpty(locationNo)){
                    throw new RuntimeException("请录入仓位");
                }
            } else {
                if (VtuzxUtil.isEmpty(locationNo)){
                    locationNo = "";
                }
            }
            if ( isLocation && null != locationList ){
                if (!locationList.contains(locationNo)){
                    throw new RuntimeException("仓位不属于当前仓库，请重试");
                }
            }
            fqty += realQty;
            Map<String,Object> stockMap =new HashMap<>();
            stockMap.put("stockName",stockName);
            stockMap.put("stockNo",stockNo);
            stockMap.put("locationNo",locationNo);
            stockMap.put("realQty",realQty);
            dataMap.put(detailNo + id,stockMap);

            trayStockNo = stockNo;
            trayLocationNo = locationNo;
        }
        double outFailQty = 0.0;//外协不良数量(质检填写的不合格数量)
        double failCount = 0.0;//废料数量

        //数据库添加仓位信息
        for (PrdInstockDetail prdInstockDetail : prdInstockDetailList){
            String billNo1 = prdInstockDetail.getFBILLNO();
            Long id = prdInstockDetail.getId();
            Double outunqualityqty = prdInstockDetail.getOUTUNQUALITYQTY();//外协不合格数量
            Double unqualityqty = prdInstockDetail.getUNQUALITYQTY();//不合格数量(质检)
            outFailQty += outunqualityqty;
            failCount += unqualityqty;
            Map<String,Object> stockMap = VtuzxUtil.getObject(dataMap,billNo1 + id);
            String locationNo = VtuzxUtil.getString(stockMap,"locationNo");
            String stockNo = VtuzxUtil.getString(stockMap,"stockNo");
            String stockName = VtuzxUtil.getString(stockMap,"stockName");
//            double realQty = VtuzxUtil.getDouble(stockMap,"realQty");
            prdInstockDetail.setFLOCATIONNUMBER(locationNo);
            prdInstockDetail.setFSTOCKNAME(stockName);
            prdInstockDetail.setFSTOCKNUMBER(stockNo);
            prdInstockDetail.setFLOT(inStockTime.substring(0,10));
//            prdInstockDetail.setFREALQTY(realQty);
        }
        prdInstockDetailService.saveOrUpdateBatch(prdInstockDetailList);

        //修改外层表单据为审核状态，添加审核时间和审核人
        prdInstock.setAUDITTIME(new DateTime());
        prdInstock.setAUDITUSERNAME(userName);
        prdInstock.setFSTATE("audit");
        prdInstock.setFQTY(fqty);
        prdInstock.setFDATE(DateUtils.strToDate(inStockTime,"yyyy-MM-dd"));


        boolean res = prdInstockService.saveOrUpdate(prdInstock);

        //审核后增加模具的使用次数
        moldMaterialService.addMoldUserCount(prdInstock);

        String trayno = prdInstock.getTRAYNO();//托盘编号



        //传金蝶入库单
        try {
            //判断是否有外协不良，如果有的话传金蝶退料单
            if ( outFailQty > 0){
                syncKingdeeOrderService.syncPrdReturn(user_id,prdInstock,prdInstockDetailList, outFailQty);
            }
            syncKingdeeOrderService.syncPrdInsStock(user_id,prdInstock,prdInstockDetailList);
            //如果有报废数量的话需要入到回材库
            if ( failCount > 0){
                syncKingdeeOrderService.syncPrdInsStockHuiCai(user_id,prdInstock,prdInstockDetailList,failCount);
            }

        } catch (Exception e){
            prdInstock.setFSTATE("save");
            prdInstockService.saveOrUpdate(prdInstock);
            throw new RuntimeException(e.getMessage());
        }
        //入库后增加托盘仓位信息
        trayService.updateTrayLocation(trayno,trayStockNo,trayLocationNo,inStockTime);
        return true;
    }



    /**
     * 从工序巡检生成入库单
     * @param master
     * @param map
     * @param userName
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createPrdInstockByCheck(Map<String, Object> master, Map<String, Object> map, String userName,Long user_id) throws Exception {

        String operNo = VtuzxUtil.getString(master,"operpNo");//工序号

        String ERPBIllNo = VtuzxUtil.getString(master,"erpBillNo");//工序计划单号

        String moBillNo = VtuzxUtil.getString(master,"prdBillNo");//生产订单号
        String departNo = VtuzxUtil.getString(master,"workShopNo");//车间编码
        String departName = VtuzxUtil.getString(master,"workShopName");//车间名称

        String materialNo =  VtuzxUtil.getString(map,"materialNo");
        String materialName =  VtuzxUtil.getString(map,"materialName");
        String specification =  VtuzxUtil.getString(map,"specification");
        String unitNo =  VtuzxUtil.getString(map,"unitNo");
        String unitName =  VtuzxUtil.getString(map,"unitName");
        //金蝶查询当前物料的默认仓库
        Map<String, Object> materialMap = materialStock(user_id,materialNo);
        String stockNumber = VtuzxUtil.getString(materialMap,"stockNo");
        String stockName = VtuzxUtil.getString(materialMap,"stockName");
        boolean FIsBatchManage = VtuzxUtil.getBoolean(materialMap,"FIsBatchManage");//是否启用批号
        //实收数量为当前工序计划单向下的所有汇报单的合格数量
        Double count = VtuzxUtil.getDouble(map,"endQty") - VtuzxUtil.getDouble(map,"unQuaqty");
//        if(VtuzxUtil.isEmpty(stockNumber)){
//            throw new RuntimeException(String.format("物料:%s,没有默认仓库请维护",materialNo));
//        }
        PrdInstock prdInstock = new PrdInstock();
        String billNo = IXqcConst.createBillNo(BillType.SCRK);
        prdInstock.setFBillNo(billNo);
        prdInstock.setFCREATEUSER(userName);
        prdInstock.setFSTATE("save");//保存状态
        prdInstock.setFWORKSHOPNO(departNo);
        prdInstock.setFWORKSHOPNAME(departName);
        prdInstock.setCreateTime(new Date());
        //砂芯和毛坯车间的不用质检
        if (departName.contains("砂芯") || departName.contains("毛坯")){
            prdInstock.setISQUALITY(true);
        } else {
            prdInstock.setISQUALITY(false);
        }

        prdInstock.setPROPLANNO(ERPBIllNo);//工序计划单号
        prdInstock.setFBILLNOMO(moBillNo);//生产订单号

        PrdInstockDetail prdInstockDetail = new PrdInstockDetail();
        prdInstockDetail.setFBILLNO(billNo);
        prdInstockDetail.setFMATERIALNAME(materialName);
        prdInstockDetail.setFMATERIALNUMBER(materialNo);
        prdInstockDetail.setFSPECIFICATION(specification);
        prdInstockDetail.setFUNITID(unitNo);
        prdInstockDetail.setFUNITNAME(unitName);
        prdInstockDetail.setFSTOCKNAME(stockName);
        prdInstockDetail.setFSTOCKNAME(stockName);
        prdInstockDetail.setFSTOCKNUMBER(stockNumber);
        prdInstockDetail.setUNQUALITYQTY(0.0);
        prdInstockDetail.setOUTUNQUALITYQTY(0.0);
        if (FIsBatchManage){
            prdInstockDetail.setFLOT("999");
        } else {
            prdInstockDetail.setFLOT("");
        }
        prdInstockDetail.setFMUSTQTY(count);
        prdInstockDetail.setFREALQTY(count);

        boolean inSave = prdInstockService.save(prdInstock);
        boolean detailSave = prdInstockDetailService.save(prdInstockDetail);
        //创建入库单后要修改工序汇报单中是否生成入库单的状态
        updatePushDown(ERPBIllNo,operNo);
        return inSave && detailSave;
    }

    /**
     * 包装间生成入库单
     * @param userName
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createPrdInstockPackage(Long user_id, String userName, SfcOptrptPackage sfcOptrptPackage) throws Exception {
        List<PrdInstockDetail> prdInstockDetailList = new ArrayList<>();

        String moBillNo = sfcOptrptPackage.getMoBillNo();//生产订单号
        String specification =  sfcOptrptPackage.getSpecification();
        //查询工序计划单获取物料信息
        SfcProplan sfcProplan = sfcProplanDao.selectOne(new LambdaQueryWrapper<SfcProplan>()
                .eq(SfcProplan::getMoBillNo, moBillNo).last("limit 1"));

        //实收数量为汇报的合格数量
        Double count = sfcOptrptPackage.getQuaQty();
        PrdInstock prdInstock = new PrdInstock();
        String billNo = IXqcConst.createBillNo(BillType.SCRK);
        prdInstock.setFBillNo(billNo);
        prdInstock.setFCREATEUSER(userName);
        prdInstock.setFSTATE("audit");//保存状态
        prdInstock.setFWORKSHOPNO("BZ");
        prdInstock.setFWORKSHOPNAME("包装车间");
        prdInstock.setCreateTime(new Date());
        prdInstock.setISQUALITY(true);
        prdInstock.setPROPLANNO(sfcOptrptPackage.getPlanNo());//工序计划单号
        prdInstock.setFBILLNOMO(moBillNo);//生产订单号
        prdInstock.setREPORTNO(sfcOptrptPackage.getBillNo());

        PrdInstockDetail prdInstockDetail = new PrdInstockDetail();
        prdInstockDetail.setFBILLNO(billNo);
        prdInstockDetail.setFMATERIALNAME(sfcProplan.getMaterialName());
        prdInstockDetail.setFMATERIALNUMBER(sfcProplan.getMaterialNo());
        prdInstockDetail.setFSPECIFICATION(specification);
        prdInstockDetail.setFUNITID(sfcProplan.getUnitNo());
        prdInstockDetail.setFUNITNAME(sfcProplan.getUnitName());
        prdInstockDetail.setFSTOCKNAME("出货成品库");
        prdInstockDetail.setFSTOCKNUMBER("CK016");
        prdInstockDetail.setUNQUALITYQTY(0.0);
        prdInstockDetail.setOUTUNQUALITYQTY(0.0);
        prdInstockDetail.setFMUSTQTY(count);
        prdInstockDetail.setFREALQTY(count);
        prdInstockDetailList.add(prdInstockDetail);

        boolean inSave = prdInstockService.saveOrUpdate(prdInstock);
        boolean detailSave = prdInstockDetailService.saveOrUpdateBatch(prdInstockDetailList);
        //传金蝶入库单
        try {
            syncKingdeeOrderService.syncPrdInsStockPackage(user_id,prdInstock,prdInstockDetailList,sfcOptrptPackage);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

        return true;
    }

    /**
     * 库管入库详情
     * @param user_id
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getprdinstockdeKu(Long user_id, Map<String, Object> map) throws Exception {
        String billNo = map.get("billNo").toString();
        PrdInstock prdinstockform = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getFBillNo,billNo));
        Boolean isquality = prdinstockform.getISQUALITY();
        //校验是否质检，没有质检的话无法传金蝶
        if (!isquality){
            throw new RuntimeException("当前托盘没有质检,请联系质检员");
        }
        if("audit".equals(prdinstockform.getFSTATE())){
            throw new RuntimeException("单据已审核");
        }

        List<PrdInstockDetail> prdinstockdetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO,billNo));
        List<Map<String, Object>> stockList = selectStcokList(user_id);
        for (PrdInstockDetail prdInstockDetail : prdinstockdetailList){
            String stockNo = prdInstockDetail.getFSTOCKNUMBER();
            //金蝶查询当前仓库是否启用仓位
            Boolean aBoolean = stockIsLoc(stockNo);
            //查询仓库向下的仓位集合
            if (aBoolean){
                List<String> locationList = getlocationList(stockNo);
                prdInstockDetail.setLocationList(locationList);
            }
            prdInstockDetail.setIsLocation(aBoolean);
            prdInstockDetail.setStockList(stockList);
        }
        Map<String,Object> data = new HashMap<>();
        //重新获取日期
        Date date = DateUtils.adjustDateIntock(new Date(), prdinstockform.getFWORKSHOPNAME());
        prdinstockform.setFDATE(date);
        data.put("data",prdinstockform);
        data.put("dataList",prdinstockdetailList);
        return data;
    }

    @Override
    public Map<String, Object> getProInstocklistQuality(SysAdmin user,Map<String, Object> map) throws Exception {
        int pageIndex = VtuzxUtil.getInt(map,"pageIndex");
        int pageSize = VtuzxUtil.getInt(map,"pageSize");
        String billNo = VtuzxUtil.getString(map,"billNo");//订单号
        String produceStr = user.getProduceList();
        List<String> produceNoList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(produceStr)){
            produceNoList = Arrays.asList(produceStr.split(","));
        }
        boolean quality = VtuzxUtil.getBoolean(map,"quality");//是否质检
        List<PrdInstock> dataList = prdInstockDao.getProInstocklist(pageSize,pageIndex * pageSize,billNo,quality,produceNoList);
        if (VtuzxUtil.isEmpty(dataList)){
            throw new RuntimeException("暂无入库信息,请确认机加是否汇报完毕");
        }
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",dataList);
        return data;
    }

    @Override
    public Map<String, Object> getInStockByTray(Map<String, Object> map) throws Exception {
        String trayNo = VtuzxUtil.getString(map,"trayNo");//托号啊
        String inStockNo = VtuzxUtil.getString(map,"inStockNo");//原入库单号
        PrdInstock prdInstock = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getTRAYNO, trayNo)
                .eq(PrdInstock::getFWORKSHOPNAME, "机加车间"));
        if (prdInstock.getFBillNo().equals(inStockNo)){
            throw new RuntimeException("合托的码与原托码一样,无法合并");
        }
        if (VtuzxUtil.isEmpty(prdInstock)){
            throw new RuntimeException("托号信息不存在,请确认");
        }
        if ("audit".equals(prdInstock.getFSTATE())){
            throw new RuntimeException("需要合并的托号已审核,请重新扫描");
        }
        PrdInstockDetail prdInstockDetail = prdInstockDetailDao.selectOne(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO, prdInstock.getFBillNo()));//需要合托的入库详情信息
        PrdInstockDetail currentDetail = prdInstockDetailDao.selectOne(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO, inStockNo));//原托的入库详情
        //判断合托的物料与原托的物料是否一致
        if (!prdInstockDetail.getFMATERIALNUMBER().equals(currentDetail.getFMATERIALNUMBER())){
            throw new RuntimeException("合托的物料与原物料不一致,无法合托");
        }
        prdInstockDetail.setSOURCENO(inStockNo);
        boolean b = prdInstockDetailService.saveOrUpdate(prdInstockDetail);

        Map<String,Object> data = new HashMap<>();
        data.put("res",b);

        return data;
    }

    /**
     * 合托的查询入库明细
     * @param user_id
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getprdinstockdeKuMerge(Long user_id, Map<String, Object> map) throws Exception {
        String billNo = map.get("billNo").toString();
        PrdInstock prdinstockform = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getFBillNo,billNo));
        Boolean isquality = prdinstockform.getISQUALITY();
        //校验是否质检，没有质检的话无法传金蝶
        if (!isquality){
            throw new RuntimeException("当前托盘没有质检,请联系质检员");
        }
        if("audit".equals(prdinstockform.getFSTATE())){
            throw new RuntimeException("单据已审核");
        }

        List<PrdInstockDetail> prdinstockdetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getFBILLNO,billNo));
//        List<Map<String, Object>> stockList = selectStcokList(user_id);
//        for (PrdInstockDetail prdInstockDetail : prdinstockdetailList){
//            String stockNo = prdInstockDetail.getFSTOCKNUMBER();
//            //金蝶查询当前仓库是否启用仓位
//            Boolean aBoolean = stockIsLoc(stockNo);
//            //查询仓库向下的仓位集合
//            if (aBoolean){
//                List<String> locationList = getlocationList(stockNo);
//                prdInstockDetail.setLocationList(locationList);
//            }
//            prdInstockDetail.setIsLocation(aBoolean);
//            prdInstockDetail.setStockList(stockList);
//        }
        //查询有没有合托的入库信息
        List<PrdInstockDetail> sourceList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                .eq(PrdInstockDetail::getSOURCENO, billNo));
        if (!VtuzxUtil.isEmpty(sourceList)){
            prdinstockdetailList.addAll(sourceList);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("data",prdinstockform);
        data.put("dataList",prdinstockdetailList);
        return data;
    }

    /**
     * 删除合托的信息
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean deleteMerge(Map<String, Object> map) throws Exception {
        Long id = VtuzxUtil.getLong(map,"id");
        int update = prdInstockDetailDao.update(null, Wrappers.<PrdInstockDetail>lambdaUpdate()
                .eq(PrdInstockDetail::getId, id)
                .set(PrdInstockDetail::getSOURCENO, ""));
        if (update > 0){
            return true;
        } else {
            return false;
        }

    }

    /**
     * 合并托盘
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> mergeTrayPda(String userName, Map<String, Object> map) throws Exception {
        List<Map<String,Object>> dataList = VtuzxUtil.getObject(map,"detail");//入库明细信息(需要合并的)
        Double sumQty = 0.0;
        List<String> fbillNoList = new ArrayList<>();
        for (Map<String,Object> data : dataList){
            Double fqty = VtuzxUtil.getDouble(data,"frealqty");
            sumQty += fqty;
            String fbillNo = VtuzxUtil.getString(data,"fbillno");//入库单号
            if (!fbillNoList.contains(fbillNo)){
                fbillNoList.add(fbillNo);
            }
        }
        //查询入库外层表，获取托盘信息
        List<PrdInstock> prdInstocks = prdInstockDao.selectList(new LambdaQueryWrapper<PrdInstock>()
                .in(PrdInstock::getFBillNo, fbillNoList));

        List<String> trayNos = prdInstocks.stream()//托号集合
                .map(PrdInstock::getTRAYNO)
                .filter(Objects::nonNull)
                .distinct() // ✅去重，根据需求可删除
                .collect(Collectors.toList());

        PrdIronTray prdIronTray = new PrdIronTray();
        String billNo = IXqcConst.createBillNo(BillType.IRON);//合并后的托盘号
        prdIronTray.setBillNo(billNo);
        prdIronTray.setCreateUserName(userName);
        prdIronTray.setCreateTime(new Date());
        prdIronTray.setFqty(sumQty);
        prdIronTray.setMaterialNo(VtuzxUtil.getString(dataList.get(0),"fmaterialnumber"));
        prdIronTray.setMaterialName(VtuzxUtil.getString(dataList.get(0),"fmaterialname"));
        prdIronTray.setSpecification(VtuzxUtil.getString(dataList.get(0),"fspecification"));
        prdIronTray.setUnitNo(VtuzxUtil.getString(dataList.get(0),"funitid"));
        prdIronTray.setUnitName(VtuzxUtil.getString(dataList.get(0),"funitname"));
        prdIronTray.setIsPackage(false);
        prdIronTray.setInStockTime(new Date());
        prdIronTray.setStockNo("CK004");//仓库默认
        prdIronTray.setStockName("机加成品库");
        prdIronTray.setLocationNo("998");
        prdIronTray.setLocationName("初始化");
        prdIronTray.setTrayNo(String.join(",",trayNos));

        //修改原托的合并状态
        trayDao.update(null,Wrappers.<Tray>lambdaUpdate()
                .in(Tray::getFBILLNO,trayNos)
                .set(Tray::getISSOURCE,true)
                .set(Tray::getIRONNO,billNo));
        boolean b = prdIronTrayService.saveOrUpdate(prdIronTray);
        Map<String,Object> data = new HashMap<>();
        data.put("ironNo",billNo);
        data.put("fqty",sumQty);
        return data;
    }

    /**
     * 审核生产入库托码合并的
     * @param user_id
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean auditPrdInMerge(Long user_id, String userName, Map<String, Object> map) throws Exception {
        List<Map<String,Object>> dataList = VtuzxUtil.getObject(map,"dataList");
        for (Map<String,Object> data : dataList){
            String billNo = VtuzxUtil.getString(data,"fbillno");
            String inStockTime = VtuzxUtil.getString(map,"inStockTime");
            PrdInstock prdInstock = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>().eq(PrdInstock::getFBillNo, billNo));
            List<PrdInstockDetail> prdInstockDetailList = prdInstockDetailDao.selectList(new LambdaQueryWrapper<PrdInstockDetail>()
                    .eq(PrdInstockDetail::getFBILLNO, billNo));
            Map<String,Object> dataMap = new HashMap<>();//key:单号+id.val:仓库，仓位，仓库名称,实收数量
            Double fqty = 0.0;//入库外层收货数量
            String trayLocationNo = "";//仓位，托盘入到哪个仓位
            String trayStockNo = "";//仓库

                int id = VtuzxUtil.getInt(data,"id");
                String detailNo = VtuzxUtil.getString(data,"fbillno");
                String stockNo = VtuzxUtil.getString(data,"fstocknumber");
                String stockName = VtuzxUtil.getString(data,"fstockname");
                String locationNo = VtuzxUtil.getString(data,"locationNo");
                boolean isLocation = VtuzxUtil.getBoolean(data,"isLocation");
                double realQty = VtuzxUtil.getDouble(data,"frealqty");//实收数量

                fqty += realQty;
//                Map<String,Object> stockMap =new HashMap<>();
//                stockMap.put("stockName",stockName);
//                stockMap.put("stockNo",stockNo);
//                stockMap.put("locationNo",locationNo);
//                stockMap.put("realQty",realQty);
//                dataMap.put(detailNo + id,stockMap);

                trayStockNo = stockNo;
                trayLocationNo = locationNo;

            double outFailQty = 0.0;//外协不良数量(质检填写的不合格数量)
            double failCount = 0.0;//废料数量

            //数据库添加仓位信息
            for (PrdInstockDetail prdInstockDetail : prdInstockDetailList){

                Double outunqualityqty = prdInstockDetail.getOUTUNQUALITYQTY();//外协不合格数量
                Double unqualityqty = prdInstockDetail.getUNQUALITYQTY();//不合格数量(质检)
                outFailQty += outunqualityqty;
                failCount += unqualityqty;
                prdInstockDetail.setFLOCATIONNUMBER("998");
                prdInstockDetail.setFSTOCKNAME("机加成品库");
                prdInstockDetail.setFSTOCKNUMBER("CK004");
                prdInstockDetail.setFLOCATIONNAME("初始化");

            }
            prdInstockDetailService.saveOrUpdateBatch(prdInstockDetailList);

            //修改外层表单据为审核状态，添加审核时间和审核人
            prdInstock.setAUDITTIME(new DateTime());
            prdInstock.setAUDITUSERNAME(userName);
            prdInstock.setFSTATE("audit");
            prdInstock.setFQTY(fqty);
            prdInstock.setFDATE(DateUtils.strToDate(inStockTime,"yyyy-MM-dd"));

            boolean res = prdInstockService.saveOrUpdate(prdInstock);
            //审核后增加模具的使用次数
            moldMaterialService.addMoldUserCount(prdInstock);

            String trayno = prdInstock.getTRAYNO();//托盘编号

            //入库后增加托盘仓位信息
            trayService.updateTrayLocation(trayno,trayStockNo,trayLocationNo,inStockTime);

            //传金蝶入库单
            try {
                //判断是否有外协不良，如果有的话传金蝶退料单
                if ( outFailQty > 0){
                    syncKingdeeOrderService.syncPrdReturn(user_id,prdInstock,prdInstockDetailList, outFailQty);
                }
                syncKingdeeOrderService.syncPrdInsStock(user_id,prdInstock,prdInstockDetailList);
                //如果有报废数量的话需要入到回材库
                if ( failCount > 0){
                    syncKingdeeOrderService.syncPrdInsStockHuiCai(user_id,prdInstock,prdInstockDetailList,failCount);
                }

            } catch (Exception e){
                prdInstock.setFSTATE("save");
                prdInstockService.saveOrUpdate(prdInstock);
                throw new RuntimeException(e.getMessage());
            }
        }



        return true;
    }

    /**
     * 创建生产入库单
     * @param map
     * @param username
     * @return
     * @throws Exception
     */
    public boolean createPrdInstock(Map<String,Object> map,String username,Long user_id,String reportNo,Double failCount) throws Exception{
        Map<String,Object> operpData = VtuzxUtil.getObject(map,"operpData");
        Map<String,Object> header = VtuzxUtil.getObject(map,"header");
        String operNo = VtuzxUtil.getString(operpData,"operNo");//工序号
        String trayNo = VtuzxUtil.getString(map,"trayNo");//工序号

        String ERPBIllNo = VtuzxUtil.getString(header,"billNo");//工序计划单号

        String moBillNo = VtuzxUtil.getString(header,"moBillNo");//生产订单号
        String departNo = VtuzxUtil.getString(operpData,"departNo");//车间编码
        String departName = VtuzxUtil.getString(operpData,"departName");//车间名称

        String materialNo =  VtuzxUtil.getString(header,"materialNo");
        String materialName =  VtuzxUtil.getString(header,"materialName");
        String specification =  VtuzxUtil.getString(header,"specification");
        String unitNo =  VtuzxUtil.getString(header,"unitNo");
        String unitName =  VtuzxUtil.getString(header,"unitName");
        //金蝶查询当前物料的默认仓库
        Map<String, Object> materialMap = materialStock(user_id,materialNo);
        String stockNumber = VtuzxUtil.getString(materialMap,"stockNo");
        String stockName = VtuzxUtil.getString(materialMap,"stockName");
        boolean FIsBatchManage = VtuzxUtil.getBoolean(materialMap,"FIsBatchManage");//是否启用批号

        //实收数量为托盘上的数量
        Tray tray = trayDao.selectOne(new LambdaQueryWrapper<Tray>()
                .eq(Tray::getFBILLNO, trayNo));
        Double count = tray.getFQTY();
        PrdInstock prdInstock = new PrdInstock();
        String billNo = BillNoGenerator.createBillNo(BillType.SCRK);
        prdInstock.setFBillNo(billNo);
        prdInstock.setFCREATEUSER(username);
        prdInstock.setFSTATE("save");//保存状态
        prdInstock.setFWORKSHOPNO(departNo);
        prdInstock.setFWORKSHOPNAME(departName);
        prdInstock.setCreateTime(new Date());
        prdInstock.setISQUALITY(false);
        prdInstock.setREPORTNO(reportNo);//工序汇报单号
        prdInstock.setPROPLANNO(ERPBIllNo);//工序计划单号
        prdInstock.setFBILLNOMO(moBillNo);//生产订单号
        prdInstock.setTRAYNO(trayNo);
        //判断入库日期机加27号往后的算作次月1号，铸造26号7点以后的算作次月一号
//        Date fdate = DateUtils.adjustDateIntock(new Date(), departName);
        prdInstock.setFDATE(new Date());

        PrdInstockDetail prdInstockDetail = new PrdInstockDetail();
        prdInstockDetail.setFBILLNO(billNo);
        prdInstockDetail.setFMATERIALNAME(materialName);
        prdInstockDetail.setFMATERIALNUMBER(materialNo);
        prdInstockDetail.setFSPECIFICATION(specification);
        prdInstockDetail.setFUNITID(unitNo);
        prdInstockDetail.setFUNITNAME(unitName);
        prdInstockDetail.setFSTOCKNAME(stockName);
        prdInstockDetail.setFSTOCKNUMBER(stockNumber);
        prdInstockDetail.setUNQUALITYQTY(failCount);
        prdInstockDetail.setOUTUNQUALITYQTY(0.0);//外协不合格数量
        prdInstockDetail.setFAILQTY(failCount);//工序汇报废料数量合计
        if (FIsBatchManage){

//            Date instocktime = tray.getINSTOCKTIME();
            prdInstockDetail.setFLOT(tray.getFLOT());
        } else {
            prdInstockDetail.setFLOT("");
        }
        prdInstockDetail.setFMUSTQTY(count);
        prdInstockDetail.setFREALQTY(count);

        boolean inSave = prdInstockService.save(prdInstock);
        boolean detailSave = prdInstockDetailService.save(prdInstockDetail);
        //创建入库单后要修改工序汇报单中是否生成入库单的状态
        updatePushDown(ERPBIllNo,operNo);
        return inSave && detailSave;
    }


    /**
     * 修改汇报单中是否下推入库的状态
     * @param ERPBIllNo 工序计划单
     * @return
     */
    private Boolean updatePushDown(String ERPBIllNo,String operNo) throws Exception{

        List<SfcOptrpt> sfcOptrpts = sfcOptrptDao.selectList(new LambdaQueryWrapper<SfcOptrpt>()
                .eq(SfcOptrpt::getErpBillNo, ERPBIllNo)
                .eq(SfcOptrpt::getOperpNo,operNo)
                .eq(SfcOptrpt::getPushDown,false));

        for (SfcOptrpt sfcOptrpt : sfcOptrpts){
            sfcOptrpt.setPushDown(true);
        }
        boolean b = sfcOptrptService.saveOrUpdateBatch(sfcOptrpts);

        return b;
    }

    /**
     * 查询入库单中的入库数量
     * @param ERPBIllNo 工序计划单
     * @return
     */
    private Double inStockCount(String ERPBIllNo,String operNo) throws Exception{
        //实收数量为，当前工序号所汇报的所有没生成入库单的数量
        List<SfcOptrpt> sfcOptrpts = sfcOptrptDao.selectList(new LambdaQueryWrapper<SfcOptrpt>()
                .eq(SfcOptrpt::getErpBillNo, ERPBIllNo)
                .eq(SfcOptrpt::getOperpNo,operNo)
                .eq(SfcOptrpt::getPushDown,false));
        List<String> operpNoList = new ArrayList<>();//汇报单号集合
        for (SfcOptrpt sfcOptrpt : sfcOptrpts){
            String billNo = sfcOptrpt.getBillNo();
            if (!operpNoList.contains(billNo)){
                operpNoList.add(billNo);
            }
        }
        //查询单据体然后汇总信息
        List<SfcOptrptDetail> sfcOptrptDetails = sfcOptrptDetailDao.selectList(new LambdaQueryWrapper<SfcOptrptDetail>()
                .in(SfcOptrptDetail::getBillNo, operpNoList));
        Double count = 0.0;
        for (SfcOptrptDetail sfcOptrptDetail : sfcOptrptDetails){
            Double quaQty = sfcOptrptDetail.getQuaQty();//合格水量
            count += quaQty;
        }

        return count;
    }


    /**
     * 判断物料是否启用批号
     * @param materialNo
     * @return
     */
    private Map<String,Object> materialStock(Long user_id, String materialNo) throws Exception{
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        String stockNo = "";
        String stockName = "";
        boolean FIsBatchManage = false;//是否启用批号
        //查询物料是够启用批号
        List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FStockId.FNumber",//默认仓库
                        "FStockId.FName",//默认仓库名称
                        "FIsBatchManage"//是否启用批次
                ),
                String.format("FNumber = '%s'", materialNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(materialQuery)) {
            stockNo = VtuzxUtil.getString(materialQuery.get(0),"FStockId.FNumber");
            stockName = VtuzxUtil.getString(materialQuery.get(0),"FStockId.FName");
            FIsBatchManage = VtuzxUtil.getBoolean(materialQuery.get(0),"FIsBatchManage");
        }
        Map<String,Object> data = new HashMap<>();
        data.put("stockNo",stockNo);
        data.put("stockName",stockName);
        data.put("FIsBatchManage",FIsBatchManage);
        return data;
    }
}

